import java.io.IOException;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.regex.Matcher;

public class SimClient extends Client implements ClientListener {

	private LocalDateTime lastSimCompleted = null;
	private LocalDateTime simStartedAt = null;
	private LocalDateTime simStoppedAt = null;
	
	public SimClient(Server server, Socket socket) throws IOException {
		super(server, socket);
		addMessageListener(this);
	}

	@Override
	public void messageRecieved(Client source, String message) {
		System.out.println(source.getInetAddress()+": "+message);
		
		// Handle Simulation Complete messages
		Matcher m;
		if((m = Messages.SIM_COMPLETE.matcher(message)).matches()) {
			if(simStartedAt != null) {
	            lastSimCompleted = LocalDateTime.now();
	            
	            System.out.printf("Simulation for %s where w = %s is complete. Z = %s\n",
	            			m.group(1), m.group(2), m.group(3));
			}
			else {
				sendMsg(Messages.ERROR, 1,"Simulations have not yet been started.");
			}
        }
		else if(Messages.SIM_START.matcher(message).matches()) {
			if(simStartedAt == null) {
				simStartedAt = LocalDateTime.now();
				simStoppedAt = null;
				System.out.println("Simulations started by "+source.getInetAddress()+".");
			}
			else {
				sendMsg(Messages.ERROR, 3,"Simulations have already been recorded as running.");
			}
		}
		else if(Messages.SIM_END.matcher(message).matches()) {
			if(simStoppedAt == null) {
				simStoppedAt = LocalDateTime.now();
				System.out.println("Simulations ended by "+source.getInetAddress()+".");
			}
			else {
				sendMsg(Messages.ERROR, 5, "Simulations are not running.");
			}
		}
		else if((m = Messages.ERROR.matcher(message)).matches()) {
			System.out.printf("Error recieved from client %s: %s\n", getInetAddress(), m.group(1));
		}
		else if(Messages.TERMINATION.matcher(message).matches());
		else {
			sendMsg(Messages.ERROR, 1, "\""+message+"\" is unrecognized or has improper syntax.");
		}
	}
	
	public boolean simulationsRunning() {
		return simStartedAt != null && simStoppedAt == null;
	}
}
